Connecting to Elasticsearch Server via Different programming Languages
In order to store or access the data inside a Elasticsearch database, you first need to connect to the Elasticsearch database server. We will show you the sample codes to connect your Elasticsearch via Java and Python.
Connecting via Java
package elasticsearch_connection;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.Unirest;
public class ElasticSearchConnection {
public static void main(String[] args) {
String host = "elasticsearch-xxxx-0.cloudclusters.net";// change it to your database server name
int port = 4608; // change it to your database server port
String userName = "your database user name";
String password = "your database password";
String auth = Base64.getEncoder().encodeToString((userName + ":" + password).getBytes());
Map<String, Object> message = new HashMap<>();
message.put("type", "text");
Map<String, Object> properties = new HashMap<>();
properties.put("no", message);
properties.put("name", message);
Map<String, Object> settings = new HashMap<>();
settings.put("number_of_shards", 1);
Map<String, Object> mappings = new HashMap<>();
mappings.put("properties", properties);
Map<String, Object> index = new HashMap<>();
index.put("settings", settings);
index.put("mappings", mappings);
HttpResponse<JsonNode> response = Unirest.put(String.format("https://%s:%d/teacher", host, port))
.header("Accept", "application/json")
.header("Authorization", "Basic " + auth)
.header("Content-Type", "application/json; utf-8")
.body(index)
.asJson();
String res = response.getBody().getObject().toString();
System.out.print(res);
//insert document
Map<String, Object> doc = new HashMap<>();
doc.put("no", "20110102");
doc.put("name", "ben");
HttpResponse<JsonNode> response2 = Unirest.post(String.format("https://%s:%d/teacher/_doc/1", host, port))
.header("Accept", "application/json")
.header("Authorization", "Basic " + auth)
.header("Content-Type", "application/json; utf-8")
.body(doc)
.asJson();
String res2 = response2.getBody().getObject().toString();
System.out.print(res2);
//get document
HttpResponse<JsonNode> response3 = Unirest.get(String.format("https://%s:%d/teacher/_doc/1", host, port))
.header("Accept", "application/json")
.header("Authorization", "Basic " + auth)
.header("Content-Type", "application/json; utf-8")
.asJson();
String res3 = response3.getBody().getObject().toString();
System.out.print(res3);
}
}
Connecting via Python
Please install Elasticsearch client end package, whose version should be 7.xx.yy, for example: pip install elasticsearch==7.17.2
The code example below is used to establish an SSL connection.
from elasticsearch import Elasticsearch
class ElasticsearchClient_SSLConnction(object):
def __init__(self):
url = "https://elasticsearch-xxxx-0.cloudclusters.net" # change it to your database server name
port = 4608 # change it to your database server port
conn = Elasticsearch(
['{}:{}'.format(url, port)],
# turn on SSL
use_ssl=True,
# make sure we verify SSL certificates
verify_certs=True,
# provide a path to CA certs on local
ca_certs='~/ca/esca.crt',
http_auth=("elastic", "your elasticsearch password")
)
self.conn = conn
def create_index(self):
mappings = {
"mappings": {
"properties": {
"name": {
"type": "keyword",
"index": "false"
},
"age": {
"type": "keyword",
"index": "false",
},
"weight": {
"type": "short",
"index": "false"
},
"birthday": {
"type": "date",
"format": "yyyy-MM-dd"
}
}
}
}
return self.conn.indices.create(index='people', body=mappings)
def insert_doc(self):
doc = {
'name': 'someone',
'age': 18,
'weight': 150,
"birthday": "2020-12-01",
}
res = self.conn.index(index="people", body=doc)
return res
- The code example below is to create a non-SSL connection.
from elasticsearch import Elasticsearch
class ElasticsearchClient_NonSSLConnction(object):
def __init__(self):
url = "https://elasticsearch-xxxx-0.cloudclusters.net" # change it to your database server name
port = 4608 # change it to your database server port
conn = Elasticsearch(
['{}:{}'.format(url, port)],
# turn off SSL
use_ssl=False,
http_auth=("elastic", "your elasticsearch password")
)
self.conn = conn